package cn.itcast.bos.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends ActionSupport implements ModelDriven<Area> {
	// 注入业务层对象
	@Autowired
	private AreaService as;
	private Area area = new Area();

	@Override
	public Area getModel() {
		// TODO Auto-generated method stub
		return area;
	}

	// 接收上传文件
	private File file;
	private String fileFileName;

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public void setFile(File file) {
		this.file = file;
	}
	//接收页面数据
	private String ids;
	public void setIds(String ids) {
		this.ids = ids;
	}

	//批量删除
	@Action(value="dele_area",results={@Result(name="success",location="./pages/base/area.html",type="redirect")})
		public String dele(){
			//分割ids
		String[] split = ids.split(",");
		//调用业务层进行删除
		as.delete(split);
		return SUCCESS;
		
	}
	// 编写批量导入数据的action
	@Action(value = "area_batchImport")
	public String batchImport() throws IOException  {
		String flag = "0";
		try{
		Workbook wk = null;
		// 先创建一个集合用来接收表中中的数据.
		List<Area> list = new ArrayList<Area>();
		// 如果导入的是xls文件用hssf,需要传入文件的路径
		if (fileFileName.endsWith(".xls")) {
			wk = new HSSFWorkbook(new FileInputStream(file));
		} else {
			wk = new XSSFWorkbook(new FileInputStream(file));
		}
		// 通过工作簿获取到要导入数据的表(sheet),索引0就是第一个表
		Sheet sheet = wk.getSheetAt(0);
		// 获取表中的每一行数据,第一行是标题需要跳过,所以进行判断
		for (Row row : sheet) {
			// 判断是否是第一行
			if (row.getRowNum() == 0) {
				continue;
			}
			// 如果数据中间有空行也进行跳过
			if (row.getCell(0) == null
					|| StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			// 封装数据
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince((row.getCell(1).getStringCellValue()));
			area.setCity((row.getCell(2).getStringCellValue()));
			area.setDistrict((row.getCell(3).getStringCellValue()));
			area.setPostcode((row.getCell(4).getStringCellValue()));
			list.add(area);
			flag="1";
		}
		// 调用业务层保存数据
		as.saveBatch(list);
		}catch(Exception e){
			e.printStackTrace();
			flag="0";
		}
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;
	}

	// 接收页面传来的参数
	private Integer page;
	private Integer rows;

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	// 条件查询的方法
	@Action(value = "area_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {

		// 封装页面数据
		Pageable pb = new PageRequest(page - 1, rows);
		Specification<Area> sf = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				// 省份条件
				if (StringUtils.isNotBlank(area.getProvince())) {
					Predicate p1 = cb.like(root.get("province")
							.as(String.class), "%" + area.getProvince() + "%");
					list.add(p1);
				}
				// 城市条件
				if (StringUtils.isNotBlank(area.getCity())) {
					Predicate p2 = cb.like(root.get("city").as(String.class),
							"%" + area.getCity() + "%");
					list.add(p2);
				}
				// 区域查询
				if (StringUtils.isNotBlank(area.getDistrict())) {
					Predicate p3 = cb.like(root.get("district")
							.as(String.class), "%" + area.getDistrict() + "%");
					list.add(p3);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		// pageData数据查询
		Page<Area> data = as.findPageData(sf, pb);
		// 将数据转换成页面需要的形式
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", data.getTotalElements());
		map.put("rows", data.getContent());
		// 将数据压入栈顶
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;

	}

}
